<?php

class ImportCommand extends CConsoleCommand
{

	public function actionInit ()
	{
		//	unlink( "/var/www/mobi03/data/www/dev.mobi03.ru/protected/runtime/ADDLOG.php" );
	}

	public function actionAnalyze ()
	{
		ini_set("memory_limit", '1024M');
		while ( true )
		{
			$sql = " select model_id, service_id, key from static WHERE mspares_ids is null limit 1000";
			$models = Yii::app()->db->createCommand( $sql )->queryAll( true );
			
			if (!$models)
				exit();
			
			$counter = 0;
			foreach ( $models as $model )
			{
				$keys = explode( "#", $model[ 'key' ] );
				$sql = " select product_id, product_title from mspares";
				$mspares = Yii::app()->db->createCommand( $sql )->queryAll( true );
				$maxSimilar = -1;
				$foundMspares = [ ];
				foreach ( $mspares as $key => $pares )
				{
					$similar = 0;
					foreach ( $keys as $keystring )
					{
						if ( empty( $keystring ) )
							continue;
						if ( strpos( $pares[ 'product_title' ], $keystring ) !== FALSE )
							$similar++;
					}
					if ( $similar > $maxSimilar and $similar > 0 )
					{
						$foundMspares[] = $pares[ 'product_id' ];
						$maxSimilar = $similar;
					}
				}
				$sql = "UPDATE static SET mspares_ids = '" . implode( ",", $foundMspares ) . "' WHERE model_id =" . $model[ 'model_id' ] . " AND service_id=" . $model[ 'service_id' ];
				Yii::app()->db->createCommand( $sql )->execute();
			}
			sleep( 2 );
		}
	}

	public function actionYandexUpdate ()
	{
		$k = 0;
		while ( true )
		{
			sleep( 5 );
			$sql = " select m.\"pageId\", b.\"pageTitle\" || ' ' || m.\"pageTitle\" as \"modelTitle\" FROM mb_pages m LEFT JOIN mb_pages b ON b.\"pageId\"=m.\"pageParent\" WHERE m.\"pageType\"='model' AND m.\"pageYandexId\"='' limit 1";
			$models = Yii::app()->db->createCommand( $sql )->queryAll( true );
			if ( !$models )
			{
				exit();
			}
			// $url = http://market.yandex.ru/search.xml?text=iphone+5s&cvredirect=2
			foreach ( $models as $model )
			{
				$url = 'http://market.yandex.ru/search.xml?cvredirect=2&text=' . urlencode( $model[ 'modelTitle' ] );
				$content = mTools::getYaContent( $url, false, 100 );
				$yaModelId = [ ];
				if ( isset( $content[ 1 ] ) && isset( $content[ 1 ][ 'redirect_url' ] ) && $content[ 1 ][ 'http_code' ] == 302 && strpos( $content[ 1 ][ 'redirect_url' ], 'captcha.xml' ) )
				{
					die( 'IP WAS BANNED' );
				}
				else if ( isset( $content[ 1 ] ) && isset( $content[ 1 ][ 'redirect_url' ] ) && $content[ 1 ][ 'http_code' ] == 302 )
				{
					// идет перенаправление на карточку товара
					preg_match( '@(.*)modelid=(\d+)(.*)@', $content[ 1 ][ 'redirect_url' ], $content );
					$yaModelId[] = $content[ 2 ];
				}
				else if ( isset( $content[ 1 ] ) && $content[ 1 ][ 'http_code' ] == 200 )
				{
					// получен контент предложений
					// print $content[ 0 ];
					Yii::import( 'ext.phpQuery.phpQuery' );

					$doc = phpQuery::newDocument( $content[ 0 ] );
					$doc = pq( $doc )->find( 'div.b-offers__list' );
					foreach ( pq( $doc )->find( 'div.b-offers_type_guru_mix' ) as $block )
					{
						$yaModelId[] = pq( $block )->attr( "id" );
					}
				}
				$yaModelId = implode( ",", $yaModelId );
				$sql = " UPDATE mb_pages SET \"pageYandexId\"='{$yaModelId}' WHERE \"pageId\"=" . $model[ 'pageId' ];
				Yii::app()->db->createCommand( $sql )->execute();
			}
			print $model[ 'pageId' ] . ":" . $k++ . "\r\n";
		}
	}

	public function actionSetNull ()
	{
		$doWhile = true;
		$counter = 0;
		while ( $doWhile )
		{
			$sql = " SELECT mb__price2item.\"itemId\" FROM mb__price2item WHERE \"priceSum\" is not null and \"priceSum\"!='' LIMIT 500 ; ";

			$rows = Yii::app()->db->createCommand( $sql )->queryAll( TRUE );
			if ( $rows )
			{
				$ids = [ ];
				foreach ( $rows as $row )
				{
					$ids[] = $row[ 'itemId' ];
				}
				$sql = " UPDATE mb__price2item SET \"priceSum\"=null WHERE \"itemId\" in (" . implode( ",", $ids ) . "); ";
				Yii::app()->db->createCommand( $sql )->execute();
				$counter++;
				print_r( $counter * 500 );
				sleep( 1 );
			}
			else
				$doWhile = false;
		}
	}

	public function actionPriceUpdate ( $post )
	{
		Yii::log( $post, 'warning' );
		$post = json_decode( $post, true );

		foreach ( $post[ 'changes' ] as $key => $value )
		{
			if ( isset( $post[ 'delete' ] ) )
			{
				foreach ( $post[ 'delete' ] as $keyA => $valueA )
				{
					$sql = "DELETE FROM {{_model2serv}} WHERE \"linkId\" = '$valueA'";
					Yii::app()->db->getCommandBuilder()->createSqlCommand( $sql )->execute();
					$sql = "DELETE FROM {{_price2item}} WHERE \"itemId\" = '$valueA'";
					Yii::app()->db->getCommandBuilder()->createSqlCommand( $sql )->execute();
				}
			}

			$ch = Model2serv::model()->find( "\"modelId\" = '{$post[ 'Model2serv' ][ 'modelId' ]}' AND \"serviceId\" = '{$value}'" );
			$m = $ch === NULL ? new Model2serv : $ch;
			$m->modelId = $post[ 'Model2serv' ][ 'modelId' ];
			$m->serviceId = $value;
			$m->blockNo = $post[ 'block' ][ $key ];
			$m->sort = $post[ 'sort' ][ $key ];
			//$m->available = $_POST['nalichie'][$key];
			$m->active = $post[ 'akt' ][ $key ];
			$m->save( false );
			$sql = "DELETE FROM {{_price2item}} WHERE \"itemId\" = '" . $m->linkId . "'";
//			echo 'delete: '.$sql.'<br />';
			Yii::app()->db->getCommandBuilder()->createSqlCommand( $sql )->query();


			foreach ( $post[ 'price' ][ $value ] as $regionID => $price )
			{
				$sql = "INSERT INTO {{_price2item}} (\"itemType\", \"itemId\", \"priceChangeDate\", \"priceSum\", \"priceRegionId\", \"priceAvailable\", \"priceAll\") VALUES ('link', '" . $m->linkId . "', '" . time() . "', '{$price}', '$regionID', '{$post[ 'nalichie' ][ $value ][ $regionID ]}', '{$post[ 'priceAll' ][ $value ]}')";
				Yii::app()->db->getCommandBuilder()->createSqlCommand( $sql )->query();
//						echo 'insert: '.$sql.'<br />';					
			}
			usleep( 50000 );
		}
//		print_r($post['price'][$value]);exit;
	}

	public function actionClean ()
	{
		$ids = include( 'ids.php');
		$sql = "  SELECT \"itemId\" from mb__price2item WHERE \"priceRegionId\"=1 ORDER BY \"itemId\" DESC ";
		$ids = [ ];
		$prices = Yii::app()->db->createCommand( $sql )->queryAll( True );
		foreach ( $prices as $price )
		{
			if ( !in_array( $price[ 'itemId' ], $ids ) )
			{
				Yii::log( $price[ 'itemId' ] . ",", "warning" );
			}
			print_r( $price );
		}
	}

	public function actionText ()
	{
		$pages = Yii::app()->dbSrc->createCommand( " select * from _pages limit 100" )->queryAll( TRUE );
		print_r( $pages );
	}

	public function actionPrices ()
	{
		set_time_limit( 0 );

		for ( $mm = 13; $mm <= 18329; $mm++ )
		{
			$sql = ' select "newModelId", "newServiceId", "Price", "serviceSort", available from mob_serv  left join mb_services on "serviceId" = "newServiceId" where "newModelId"=' . $mm;
			$prices = Yii::app()->db->createCommand( $sql )->queryAll( TRUE );
			if ( $prices )
			{
				foreach ( $prices as $price )
				{
					$result = Yii::app()->db->createCommand( " SELECT \"linkId\" FROM mb__model2serv WHERE \"modelId\"={$price[ 'newModelId' ]} AND \"serviceId\"={$price[ 'newServiceId' ]} " )->queryRow( true );
					if ( !$result )
					{
						$modServ = new Model2servMaksud();
						$modServ->modelId = $price[ 'newModelId' ];
						$modServ->serviceId = $price[ 'newServiceId' ];
						$modServ->blockNo = 0;
						$modServ->sort = $price[ 'serviceSort' ];
						$modServ->active = 1;
						$modServ->save();

						$linkId = $modServ->linkId;

						for ( $i = 1; $i <= 5; $i++ )
						{
							$query = "INSERT INTO mb__price2item VALUES('link',{$linkId},'" . time() . "',{$i},'{$price[ 'Price' ]}','',0);";
							Yii::app()->dbDest->createCommand( $query )->execute();
						}
					}
				}
			}
			usleep( 500000 );
		}
	}

	public function actionIndex ()
	{
		$query = "SELECT * FROM mb_pages limit 10";
		$rows = Yii::app()->dbDest->createCommand( $query )->queryAll( TRUE );
		print_r( $rows );

		exit;

		$fromTo = [
			5 => 1,
			6 => 3,
			7 => 6,
			10 => 8,
			14 => 7,
			16 => 2,
			18 => 5,
			24 => 4,
			31 => 10,
			8622 => 9
		];
		$cUrls = [
			1 => 'remont-telefonov',
			2 => 'remont-planshetov',
			3 => 'remont-noutbukov',
			4 => 'remont-kompyuterov',
			5 => 'remont-monoblokov',
			6 => 'remont-fotoapparatov',
			7 => 'remont-elektronnih-knig',
			8 => 'remont-mp3-pleerov',
			9 => 'remont-televizorov',
			10 => 'remont-chasov',
		];



		$query = "SELECT * FROM pages WHERE templ = 'model-list' ";
		$rows = Yii::app()->dbSrc->createCommand( $query )->queryAll( TRUE );

		foreach ( $rows as $row )
		{
			$parent = str_replace( "#", "", $row[ 'parents' ] );
			$parent = $fromTo[ $parent ];
			$query = " ({$parent},'brand','{$cUrls[ $parent ]}/{$row[ 'url' ]}','{$row[ 'title' ]}', '{$row[ 'text1' ]}', '{$row[ 'text2' ]}', '{$row[ 'url' ]}.jpg', 'list/brand', {$row[ 'id' ]} );";


			$model = new PageMaksud();
			$model->pageParent = $parent;
			$model->pageType = 'brand';
			$model->pageUrl = $cUrls[ $parent ] . '/' . $row[ 'url' ];
			$model->pageTitle = $row[ 'title' ];
			$model->pageContentShort = $row[ 'text1' ];
			$model->pageContentFull = $row[ 'text2' ];
			$model->pageImages = $row[ 'url' ] . '.jpg';
			$model->pageAction = 'list/brand';
			$model->pageSourceId = $row[ 'id' ];
			$model->save();

			$id = $model->pageId;


			$metas = [
				'itemType' => 'page',
				'itemId' => $id,
				'seoTextFull' => $row[ 'text1' ] . "<br />" . $row[ 'text2' ],
				'metaH1' => $row[ 'h1' ],
				'metaTitle' => $row[ 'metaTitle' ],
				'metaDesc' => $row[ 'metaDescription' ],
				'metaKeywords' => $row[ 'metaKeywords' ],
				'metaRobots' => $row[ 'metaRobots' ],
				'sysHeaders' => $row[ 'sysHeader' ],
			];

			Yii::app()->dbDest->getCommandBuilder()->createInsertCommand( '{{metas}}', $metas )->execute();
			unset( $metas );

			$query = " SELECT * FROM pages WHERE templ = 'model' AND parents = '" . $row[ 'parents' ] . "#" . $row[ 'id' ] . "#" . "'; ";
			$models = Yii::app()->dbSrc->createCommand( $query )->queryAll( TRUE );

			foreach ( $models as $sModel )
			{
				$model = new PageMaksud();
				$model->pageParent = $id;
				$model->pageType = 'model';
				$model->pageUrl = $cUrls[ $parent ] . '/' . $row[ 'url' ] . '/' . $sModel[ 'url' ];
				$model->pageTitle = $sModel[ 'title' ];
				$model->pageImages = $cUrls[ $parent ] . '-' . $row[ 'url' ] . '-' . $sModel[ 'url' ] . '.jpg';
				$model->pageAction = 'list/model';
				$model->pageSourceId = $sModel[ 'id' ];
				$model->save();

				// $filename = "/var/www/mobi03/data/www/mobi03.ru/images/models/" . $sModel[ 'un' ];
				// $newFile = "/var/www/mobi03/data/www/dev.mobi03.ru/uploads/images/model/" . $cUrls[ $parent ] . '-' . $row[ 'url' ] . '-' . str_replace( " ", "-", $sModel[ 'url' ] ) . '.jpg';

				$modelId = $model->pageId;

				$metas = [
					'itemType' => 'page',
					'itemId' => $modelId,
					'seoTextFull' => $sModel[ 'text1' ] . "<br />" . $sModel[ 'text2' ],
					'metaH1' => $sModel[ 'h1' ],
					'metaTitle' => $sModel[ 'metaTitle' ],
					'metaDesc' => $sModel[ 'metaDescription' ],
					'metaKeywords' => $sModel[ 'metaKeywords' ],
					'metaRobots' => $sModel[ 'metaRobots' ],
					'sysHeaders' => $sModel[ 'sysHeader' ],
				];

				Yii::app()->dbDest->getCommandBuilder()->createInsertCommand( '{{metas}}', $metas )->execute();

				if ( empty( $modelId ) )
				{
					$this->write( "CANNOT ADD MODEL:" . $sModel[ 'id' ] . "," );
					continue;
				}
				$query = "SELECT * FROM sc_modelServices WHERE modelId = " . $sModel[ 'id' ];
				$mServRows = Yii::app()->dbSrc->createCommand( $query )->queryAll( TRUE );

				if ( !$mServRows )
				{
					continue;
				}
				foreach ( $mServRows as $mServ )
				{
					$servId = Yii::app()->dbDest->createCommand( " SELECT * FROM {{services}} WHERE \"serviceSourceId\" = " . $mServ[ 'serviceId' ] )->queryRow( TRUE );
					if ( !$servId )
					{
						$this->write( "NO SERVICE:" . $mServ[ 'serviceId' ] );
						continue;
					}
					$found = Yii::app()->dbDest->createCommand( " SELECT * FROM {{_model2serv}} WHERE \"modelId\" ={$modelId} AND \"serviceId\"= {$servId[ 'serviceId' ]}" )->queryRow( TRUE );

					if ( !$found )
					{
						$modServ = new Model2servMaksud();
						$modServ->catId = $parent;
						$modServ->brandId = $id;
						$modServ->modelId = $modelId;
						$modServ->serviceId = $servId[ 'serviceId' ];
						$modServ->blockNo = 0;
						$modServ->sort = $servId[ 'serviceSort' ];
						$modServ->active = 1;
						$modServ->save();
						$linkId = $modServ->linkId;

						if ( $linkId > 0 )
						{

							if ( $mServ[ 'price' ] == "Бесплатно" )
							{
								$mServ[ 'price' ] = 0;
							}

							$mServ[ 'price' ] = preg_replace( "/\D/", "", $mServ[ 'price' ] );

							if ( $mServ[ 'price' ] == "" )
							{
								$mServ[ 'price' ] = -1;
							}

							$query = "INSERT INTO {{_price2item}} VALUES('link',{$linkId},'" . time() . "',1,{$mServ[ 'price' ]},{$mServ[ 'price' ]},0);";

							Yii::app()->dbDest->createCommand( $query )->execute();
						}
						else
						{
							$this->write( "EMPTY: " . $mServ[ 'id' ] . "," );
						}
					}
					else
					{
						$this->write( "ALREADY: " . $mServ[ 'id' ] . "," );
					}
					usleep( 500 );
				}
			}
		}
	}

	public function write ( $content )
	{
		$filename = "/var/www/mobi03/data/www/dev.mobi03.ru/protected/runtime/ADDLOG.php";

		if ( (strtoupper( substr( PHP_OS, 0, 3 ) ) == 'WIN' ) )
		{
			$filename = "D:/__localhost/mobi03/protected/runtime/ADDLOG.php";
		}

		$file = fopen( $filename, "a" );
		fwrite( $file, $content . chr( 13 ) );
		fclose( $file );
	}

	public function getStatus ( $orderNo )
	{
		$result = [
			'fio' => 'Костя Пак', // клиент
			'phones' => 'phone_no1/phone_no2/phone_no3/phone_no4/phone_no5', // все номера телефонов клиента
			'email' => 'email@mail.com', // email клиента
			'status' => 'Принята // Принят по гарантии // Заказ ЗЧ // В работе // Готов // Выдан // Без ремонта // Выдан без ремонта // Выдан по гарантии', // одно из этих статусов
			'first_sc' => 'Горбушка', // Поле Начальный СЦ
			'agreedUntil' => '13.02.2014 15:31:45', // поле Согласован до
			'callbackStatus' => 'Перезвонить 1', // Поле заявки: Перезвонить
			'agree' => 'Согласовать', // Поле заявки: Согласовать
			'manager' => 'Костантин Пак', // Поле заявки: Менеджер
			'current_sc' => 'Китай город', // Поле заявки: СЦ
			'transfer_point' => 'Китай город', // Поле заявки: Перемещение
			'received' => '13.02.2014 15:31:45', // поле Принято
			'fixed' => '13.03.2014 15:31:45', // поле Сделано
			'returned' => '13.04.2014 15:31:45', // поле Выдано
			'ssm' => '', // поле ССМ
			'snmp' => '', // поле СНПМ
			'total' => '8000', // поле ИТОГО
			'payed' => '7200', // поле ОПЛАЧЕНО
			'transfer_list' => [
				0 => [
					'create_date' => '13.04.2014 15:31:45', // дата создания
					'transfer_status' => 'В пути', // Статус доставки
					'transfer_points' => 'Из китай город в горбушку', // описание задачи
					'transfer_from' => 'Китай город', // Откуда
					'transfer_to' => 'Горбушка', // Куда
				],
				1 => [
					'create_date' => '13.07.2014 15:31:45', // дата создания
					'transfer_status' => 'В пути', // Статус доставки
					'transfer_points' => 'Из Горбушки в Центральный', // описание задачи
					'transfer_from' => 'Горбушка', // Откуда
					'transfer_to' => 'Центральный', // Куда
				],
			// количество перемещений неограничено
			],
			'payment_list' => [
				0 => [
					'pay_date' => '13.08.2014 15:31:45', // дата оплаты
					'pay_sc' => 'Горбушка', // СЦ (т.е., в какую кассу оплачено)
					'pay_type' => 'Наличные', // Счет
					'pay_detail' => 'За ремонт', // Вид оплаты
					'pay_incoming' => '5000', // Приход
					'pay_outgoing' => '', // Расход
					'pay_notice' => 'Предоплата за ремонт моего гребанного телефона', // Примечание
				],
				1 => [
					'pay_date' => '21.08.2014 15:31:45', // дата оплаты
					'pay_sc' => 'Центральный', // СЦ (т.е., в какую кассу оплачено)
					'pay_type' => 'Банковский перевод', // Счет
					'pay_detail' => 'За ремонт', // Вид оплаты
					'pay_incoming' => '2200', // Приход
					'pay_outgoing' => '', // Расход
					'pay_notice' => 'Предоплата за ремонт моего гребанного телефона', // Примечание
				],
			// количество оплат неограничено
			],
		];
	}

}
